library(tidyverse) # for graphing and data cleaning
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
library(ggthemes) # for even more plotting themes
library(geofacet) # for special faceting with US map layout
theme_set(theme_minimal()) # My favorite ggplot() theme :)
# Lisa's garden data
data("garden_harvest")
# Seeds/plants (and other garden supply) costs
data("garden_spending")
# Planting dates and locations
data("garden_planting")
# Tidy Tuesday data
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
Before starting your assignment, you need to get yourself set up on GitHub and make sure GitHub is connected to R Studio. To do that, you should read the instruction (through the “Cloning a repo” section) and watch the video here. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Expanding the data wrangling toolkit” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
garden_harvest data to find the total harvest weight in pounds for each vegetable and day of week (HINT: use the wday() function from lubridate). Display the results so that the vegetables are rows but the days of the week are columns.garden_harvest %>%
mutate(day = wday(date, label = TRUE)) %>%
group_by(vegetable, day) %>%
summarize(total_wt = sum(weight)) %>%
pivot_wider(names_from = day,
values_from = total_wt)
garden_harvest data to find the total harvest in pound for each vegetable variety and then try adding the plot from the garden_planting table. This will not turn out perfectly. What is the problem? How might you fix it?garden_harvest %>%
group_by(vegetable, variety) %>%
summarize(tot_harvest_lb = weight*0.0022) %>%
left_join(plant_date_loc,
by = c("vegetable", "variety"))
## Error in is.data.frame(y): object 'plant_date_loc' not found
The problem with this code is that not every vegetable in the garden_harvest data set has fully completed data. This means that some data has NA values. We could get rid of these NA values by using an inner join function.
garden_harvest and garden_spending datasets, along with data from somewhere like this to answer this question. You can answer this in words, referencing various join functions. You don’t need R code but could provide some if it’s helpful.In order to see how much you saved, you could combine both data sets and then sort each vegetable and variety in the garden_harvest. From there we can do an inner join by vegetable and variety which would show us price of what it would cost for each vegetable planted.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
mutate(variety = fct_reorder(variety, date, min)) %>%
group_by(variety) %>%
summarize(total_harvest_lb = sum(weight*0.0022),
min_date = min(date)) %>%
ggplot(aes(x = total_harvest_lb, y = fct_rev(variety))) +
geom_col(fill = "tomato2")+
labs(title = "Tomato Varieties Harvest Weight
In Order of Earliest to Latest First Harvest Date",
y = "",
x = "Total LBS")
garden_harvest data, create two new variables: one that makes the varieties lowercase and another that finds the length of the variety name. Arrange the data by vegetable and length of variety name (smallest to largest), with one row for each vegetable variety. HINT: use str_to_lower(), str_length(), and distinct().garden_harvest %>%
mutate(lowercase = str_to_lower(variety),
length = str_length(variety)) %>%
group_by(vegetable, variety) %>%
summarize(length = mean(length)) %>%
arrange(vegetable, length)
garden_harvest data, find all distinct vegetable varieties that have “er” or “ar” in their name. HINT: str_detect() with an “or” statement (use the | for “or”) and distinct().garden_harvest %>%
mutate(name_er_ar = str_detect(variety, "er|ar")) %>%
filter(name_er_ar == TRUE) %>%
distinct(vegetable, variety)
In this activity, you’ll examine some factors that may influence the use of bicycles in a bike-renting program. The data come from Washington, DC and cover the last quarter of 2014.
{300px}
{300px}
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data-Small.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
NOTE: The Trips data table is a random subset of 10,000 trips from the full quarterly data. Start with this small data table to develop your analysis commands. When you have this working well, you should access the full data set of more than 600,000 events by removing -Small from the name of the data_site.
It’s natural to expect that bikes are rented more at some times of day, some days of the week, some months of the year than others. The variable sdate gives the time (including the date) that the rental started. Make the following plots and interpret them:
sdate. Use geom_density().Trips %>%
ggplot(aes(x = sdate))+
geom_density()+
labs(title = "Distribution of bike rentals by date",
x = "",
y = "")
The density plot above shows the distribution of bike rentals over three months. We can see from the plot that earlier months such as October and November have more bike rentals in comparison to December. This may be attributed to the whether and temperate, as less people want to go biking the colder the weather gets.
mutate() with lubridate’s hour() and minute() functions to extract the hour of the day and minute within the hour from sdate. Hint: A minute is 1/60 of an hour, so create a variable where 3:30 is 3.5 and 3:45 is 3.75.Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60))) %>%
ggplot(aes(x = time))+
geom_density()+
labs(title = "Distribution of bike rentals by time of day",
y = "",
x = "Hours in military time")
The density plot above shows at what time during the day do most people go biking. We can see that people are most likely to go biking mid morning around hours 8-9 and between hours 17-19 after diner time. This bimodal distribution makes sense because its when most people have free time, either before work or after work.
Trips %>%
mutate(wday = wday(sdate, label = TRUE)) %>%
ggplot(aes(y = fct_rev(wday)))+
geom_bar(fill = "darkblue")+
labs(title = "Number of bike rentals by day of the week",
x = "",
y = "")
The barplot above shows the number of bike rentals by day of the week. We can see that on average more people go biking during the week rather than on weekends.
Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60)),
wday = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time))+
facet_wrap(vars(wday))+
geom_density()+
labs(title = "Distribution of bike rentals by time of day",
x = "Hours in military time",
y = "")
From these distribution graphs we can see that that there is a pattern. On weekends midday is the most popular time to rent a bike and this is because people usually don’t work on weekends. As for weekdays there is the bimodal distribution similar to the distribution graph on question eight. This makes sense because people most often have free time before and after work, and prefer to bike when it is light out, therfore giving us the two popular times to bikw which is mid morning and after dinner in the evenings.
The variable client describes whether the renter is a regular user (level Registered) or has not joined the bike-rental organization (Causal). The next set of exercises investigate whether these two different categories of users show different rental behavior and how client interacts with the patterns you found in the previous exercises.
fill aesthetic for geom_density() to the client variable. You should also set alpha = .5 for transparency and color=NA to suppress the outline of the density function.Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60)),
wday = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time, fill = client))+
facet_wrap(vars(wday))+
geom_density(alpha = .5, color = NA)+
labs(title = "Distribution of bike rentals by time of day
and client type",
x = "",
y = "")
From this distribution we can see that on average, casual riders outnumber registered clients on the weekend. We can also see that during the week that the distribution between casual and registered bikers is different. The casual riders have a normal distribution while the registered riders have a bimodal distribution.
position = position_stack() to geom_density(). In your opinion, is this better or worse in terms of telling a story? What are the advantages/disadvantages of each?Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60)),
wday = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time, fill = client))+
facet_wrap(vars(wday))+
geom_density(alpha = .5, color = NA, position = position_stack())+
labs(title = "Distribution of bike rentals by time of day
and client type",
x = "",
y = "")
This graph tells a much better story than 11. There is not as much overlap which makes it easier for us to interpret the graph. This allows us be certain when making conclusions.
position = position_stack()). Add a new variable to the dataset called weekend which will be “weekend” if the day is Saturday or Sunday and “weekday” otherwise (HINT: use the ifelse() function and the wday() function from lubridate). Then, update the graph from the previous problem by faceting on the new weekend variable.Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60)),
week_type = wday(sdate, label = TRUE),
weekend = ifelse(wday(sdate) %in% c(1,7), "weekend", "weekday")) %>%
ggplot(aes(x = time, fill = client))+
facet_wrap(vars(weekend))+
geom_density(alpha = .5, color = NA)+
labs(title = "Distribution of bike rentals by time of day, type of day,
and type of client",
x = "",
y = "")
client and fill with weekday. What information does this graph tell you that the previous didn’t? Is one graph better than the other?Trips %>%
mutate(hour = hour(sdate),
minute = minute(sdate),
time = (hour + (minute/60)),
week_type = wday(sdate, label = TRUE),
day_type = ifelse(wday(sdate) %in% c(1,7), "weekend", "weekday")) %>%
ggplot(aes(x = time, fill = day_type))+
facet_wrap(vars(client))+
geom_density(alpha = .5, color = NA)+
labs(title = "Distribution of Bike Rentals by Time of Day, Type of Day,
and Type of Client",
x = "",
y = "")
I wouldn’t say one graph is better than the other, because they both show us different things. This graph facets on client and fills with weekday rather than it being flipped for the graph for 13. This graph is more helpful if you wanted to look at the distributions within client type.
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. We will improve this plot next week when we learn about maps!Trips %>%
count(sstation) %>%
inner_join(Stations,
by = c("sstation" = "name")) %>%
ggplot(aes(x = long, y = lat, color = n))+
geom_point()+
labs(title = "Total departures from each station
by latitude and longitude",
x = "Longitude",
y = "Latitude")
Trips %>%
group_by(sstation) %>%
summarize(tot_dept = n(),
prop_casual = mean(client == "Casual")) %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
ggplot(aes(x = long, y = lat, color = prop_casual))+
geom_point(alpha = 0.5)+
labs(title = "Stations with a higher percentage
of departures by casual users",
x = "Longitude",
y = "Latitude")
I noticed this graph has a similar distribution to the graph above. We also see clusters around -77.1 longitude to -77.0 longitude. The proportions of most of the points are below 0.5 as well.
as_date(sdate) converts sdate from date-time format to date format.ten_trip <- Trips %>%
mutate(sdate = as_date(sdate)) %>%
count(sstation, sdate) %>%
slice_max(n = 10, order_by = n, with_ties = FALSE)
ten_trip
Trips %>%
mutate(sdate = as_date(sdate)) %>%
inner_join(ten_trip,
by = c("sstation", "sdate"))
DID YOU REMEMBER TO GO BACK AND CHANGE THIS SET OF EXERCISES TO THE LARGER DATASET? IF NOT, DO THAT NOW.
Trips%>%
mutate(sdate = as_date(sdate)) %>%
inner_join(ten_trip, by = c("sstation", "sdate")) %>%
mutate(day_of_week = wday(sdate, label = TRUE)) %>%
group_by(client, day_of_week) %>%
summarize(trips_day = n()) %>%
group_by(client) %>%
mutate(prop = trips_day/sum(trips_day)) %>%
pivot_wider(id_cols = day_of_week,
names_from = client,
values_from = prop)
This problem uses the data from the Tidy Tuesday competition this week, kids. If you need to refresh your memory on the data, read about it here.
facet_geo(). The graphic won’t load below since it came from a location on my computer. So, you’ll have to reference the original html on the moodle page to see it.DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?